﻿using JV.Com.Business;
using JV.Com.Internals;
using JV.Com.ViewModels.Wrapper;
using Microsoft.Practices.Prism.StoreApps;
using Microsoft.Practices.Prism.StoreApps.Interfaces;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using Windows.UI.Xaml.Navigation;

namespace JV.Com.ViewModels
{
    public sealed class SearchResultPageViewModel : PageBaseViewModel
    {
        public SearchResultPageViewModel(INavigationService navigationService)
            : base(navigationService)
        {
        }

        public override void OnNavigatedTo(object navigationParameter, NavigationMode navigationMode, Dictionary<string, object> viewModelState)
        {
            base.OnNavigatedTo(navigationParameter, navigationMode, viewModelState);
            Query = (string)navigationParameter;
        }

        public async Task<IEnumerable<SearchResultWrapper>> SearchCurrentQueryAsync()
        {
            InLoading = true;

            var items = new List<SearchResultWrapper>();

            if (string.IsNullOrEmpty(Query)) return items;

            var result = await Service.SearchGamesAsync(Query);

            foreach (var item in result)
            {
                var machine = Cache.Instance.Machines[item.Key];
                if (machine.IsOld) continue;

                var gamesByMachine = new SearchResultWrapper(this, machine.ShortName);
                foreach (var game in item.Value)
                {
                    var gameWrapper = new SearchResultGameWrapper(gamesByMachine, game);
                    gamesByMachine.Games.Add(gameWrapper);
                }
                items.Add(gamesByMachine);
            }

            SearchItems = items;

            InLoading = false;

            return items;
        }

        public override string PageTitle { get { return "Résultats"; } }
        public List<SearchResultWrapper> SearchItems { get; private set; }
    }
}
